Flatten 2D Vector

Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

  1. [
  2. [1,2],
  3. [3],
  4. [4,5,6]
  5. ]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

Hint:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.

Follow up:

As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Solution:

  1. public class Vector2D {
  2. private Iterator<List<Integer>> i;
  3. private Iterator<Integer> j;
  4. public Vector2D(List<List<Integer>> vec2d) {
  5. i = vec2d.iterator();
  6. }
  7. public int next() {
  8. hasNext();
  9. return j.next();
  10. }
  11. public boolean hasNext() {
  12. while ((j == null || !j.hasNext()) && i.hasNext())
  13. j = i.next().iterator();
  14. return j != null && j.hasNext();
  15. }
  16. }
  17. /**
  18. * Your Vector2D object will be instantiated and called as such:
  19. * Vector2D i = new Vector2D(vec2d);
  20. * while (i.hasNext()) v[f()] = i.next();
  21. */